package com.jsbj.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.base.Constants;
import com.jsbj.base.ResultBean;
import com.jsbj.enums.ConfigDictTypeEnum;
import com.jsbj.page.PageDomain;
import com.jsbj.page.TableSupport;
import com.jsbj.tools.BeanUtils;
import com.jsbj.tools.DateUtils;
import com.jsbj.tools.RequestHeaderUtils;
import com.jsbj.tools.StringUtils;
import com.jsbj.user.entities.SysPermissionAll;
import com.jsbj.user.entities.SysProject;
import com.jsbj.user.entities.SysSystem;
import com.jsbj.user.entities.SysUser;
import com.jsbj.user.mapper.SysSystemMapper;
import com.jsbj.user.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 系统表 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2022-03-07
 */
@Service
public class SysSystemServiceImpl extends ServiceImpl<SysSystemMapper, SysSystem> implements ISysSystemService {

    @Autowired
    private ISysProjectService sysProjectService;

    @Override
    public List<SysSystem> querySysByTenantCode(String tenantCode) {
        return baseMapper.querySysByTenantCode(tenantCode);
    }

    @Override
    public List<Map<String, Object>> queryGkSystem(Integer type) {
        String userId = RequestHeaderUtils.getUserId(request);
        String tenantCode = RequestHeaderUtils.getTenantCode(request);
        List<Map<String, Object>> resultList = new ArrayList<>();
        SysProject sysProject = sysProjectService.getProjectInfoByTenatCode(tenantCode);
        if(sysProject==null){
            return null;
        }
        if(sysProject.getIncludeSystem().contains(Constants.LQXT)){
            Map<String, Object> map = new HashMap<>();
            map.put("name","沥青");
            map.put("value", Constants.LQXT);
            resultList.add(map);
        }
        if(sysProject.getIncludeSystem().contains(Constants.SWXT)){
            Map<String, Object> map = new HashMap<>();
            map.put("name","水稳");
            map.put("value", Constants.SWXT);
            resultList.add(map);
        }
        if(type==1 && sysProject.getIncludeSystem().contains(Constants.SNXT)){
            Map<String, Object> map = new HashMap<>();
            map.put("name","水泥");
            map.put("value", Constants.SNXT);
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public List<SysSystem> getSystemListByProCode(String tenantCode) {
        SysProject sysProject = sysProjectService.getProjectInfoByTenatCode(tenantCode);
        if(sysProject==null){
            return null;
        }
        String systems = sysProject.getIncludeSystem();
        List<String> systemCodes = new ArrayList<>();
        if(StringUtils.isNotEmpty(systems)){
            for (String includeSystemSg : sysProject.getIncludeSystem().split(",")) {
                systemCodes.add(includeSystemSg);
            }
        }
        if(systemCodes!=null && systemCodes.size()>0){
            return baseMapper.querySysByList(systemCodes);
        }
        return null;
    }

    @Override
    public SysSystem querySystemBySysCode(String systemCode) {
        LambdaQueryWrapper<SysSystem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysSystem::getSystemCode, systemCode);
        queryWrapper.eq(SysSystem::getDisabled, 0);
        queryWrapper.last(" limit 1");
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public List<SysSystem> getSystemList() {
        LambdaQueryWrapper<SysSystem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysSystem::getDisabled, 0);
        return baseMapper.selectList(queryWrapper);
    }

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private ISysPermissionAllService sysPermissionAllService;

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public ResultBean<JSONObject> saveOrUpdateData(SysSystem sysSystem) {
        String userId = RequestHeaderUtils.getUserId(request);
        // 校验必填
        if (StringUtils.isEmpty(sysSystem.getSystemCode()) || StringUtils.isEmpty(sysSystem.getSystemName()) || StringUtils.isEmpty(sysSystem.getSystemTypeValue())) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        if (StringUtils.isEmpty(sysSystem.getSystemTypeKey())) {
            sysSystem.setSystemTypeKey("sysType");
        }
        // 校验编码和名称不能重复
        LambdaQueryWrapper<SysSystem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysSystem::getDisabled, 0);
        if (StringUtils.isNotEmpty(sysSystem.getId())) {
            queryWrapper.ne(SysSystem::getId, sysSystem.getId());
        }
        queryWrapper.and((wrapper)->{
            wrapper.eq(SysSystem::getSystemCode,sysSystem.getSystemCode())
                    .or().eq(SysSystem::getSystemName,sysSystem.getSystemName());});
        List<SysSystem> sysSystems = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(sysSystems)) {
            return new ResultBean<>().build("系统编码或者名称已存在，请重新填写！");
        }
        if (StringUtils.isEmpty(sysSystem.getId())) {
            sysSystem.setCreaterId(userId);
            sysSystem.setUpdateId(userId);
            baseMapper.insert(sysSystem);
        } else {
            SysSystem updateInfo = baseMapper.selectById(sysSystem.getId());
            BeanUtils.copyPropertiesIgnoreNull(sysSystem, updateInfo);
            updateInfo.setUpdateId(userId);
            updateInfo.setUpdateTime(new Date());
            baseMapper.updateById(updateInfo);
        }
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public SysSystem getDetail(String id) {
        SysSystem sysSystem = baseMapper.selectById(id);
        if (StringUtils.isNotEmpty(sysSystem.getSystemTypeValue())) {
            sysSystem.setSystemTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.SYSTYPE.getCode(), sysSystem.getSystemTypeValue()));
        }
        SysUser sysUser = sysUserService.getById(sysSystem.getUpdateId());
        sysSystem.setUpdateName(sysUser.getUserName());
        sysSystem.setUpdateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", sysSystem.getUpdateTime()));
        return sysSystem;
    }

    @Override
    public ResultBean<JSONObject> deleteData(String id) {
        SysSystem sysSystem = baseMapper.selectById(id);
        // 校验该系统是否绑定菜单，如果已绑定，不可删除
        List<SysPermissionAll> sysPermissionAlls = sysPermissionAllService.selectBySysCode(sysSystem.getSystemCode());
        if (CollectionUtils.isNotEmpty(sysPermissionAlls)) {
            return new ResultBean<>().build("该系统已绑定菜单，无法删除！");
        }
        sysSystem.setDisabled(1);
        String userId = RequestHeaderUtils.getUserId(request);
        sysSystem.setUpdateId(userId);
        sysSystem.setUpdateTime(new Date());
        baseMapper.updateById(sysSystem);
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public IPage<SysSystem> getListData() {
        // 如果是超级管理员再返回，否则返回空
        String userId = RequestHeaderUtils.getUserId(request);
        SysUser sysUser = sysUserService.getById(userId);

        LambdaQueryWrapper<SysSystem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysSystem::getDisabled, 0);
//        queryWrapper.orderByAsc(SysSystem::getCreateTime);
        if (!"0".equals(sysUser.getIsStatus())) {
            queryWrapper.eq(SysSystem::getId, "-1");
        }
        queryWrapper.orderByDesc(SysSystem::getCreateTime);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPage();
        Integer pageSize = pageDomain.getPageSize();
        Page<SysSystem> page = new Page<>(pageNum, pageSize);
        IPage<SysSystem> iPage = baseMapper.selectPage(page, queryWrapper);
        for (SysSystem sysSystem : iPage.getRecords()) {
            sysSystem.setSystemTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.SYSTYPE.getCode(), sysSystem.getSystemTypeValue()));
        }
        return iPage;
    }
}
